import { onMounted, watch } from "vue";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { useSettingsStore } from "../stores/settings";

export function useTheme() {
  const settingsStore = useSettingsStore();
  const currentWindow = getCurrentWindow();

  // 应用主题
  function applyTheme(theme: "light" | "dark") {
    const html = document.documentElement;
    if (theme === "dark") {
      html.classList.add("dark");
    } else {
      html.classList.remove("dark");
    }
  }

  // 获取系统主题
  async function getSystemTheme(): Promise<"light" | "dark"> {
    try {
      const theme = await currentWindow.theme();
      return theme === "dark" ? "dark" : "light";
    } catch (error) {
      console.error("Failed to get system theme:", error);
      return "light";
    }
  }

  // 更新主题
  async function updateTheme() {
    const { theme } = settingsStore.settings;
    if (theme === "system") {
      const systemTheme = await getSystemTheme();
      applyTheme(systemTheme);
    } else {
      applyTheme(theme);
    }
  }

  onMounted(async () => {
    // 加载设置
    await settingsStore.loadSettings();

    // 应用主题
    await updateTheme();

    // 监听系统主题变化
    currentWindow.onThemeChanged(async () => {
      if (settingsStore.settings.theme === "system") {
        await updateTheme();
      }
    });
  });

  // 监听主题设置变化
  watch(() => settingsStore.settings.theme, updateTheme);

  return {
    applyTheme,
    updateTheme,
  };
}
